﻿namespace Digitalmes.Application.Sys.Orgs.Commands;

/// <summary>
/// 创建组织命令。
/// </summary>
/// <param name="Org"></param>
public record CreateOrgCommand(SysOrgDto Org) : IRequest<IResult<bool>>;

internal sealed class CreateOrgCommandHandler(IRepository<SysOrg> repo) : IRequestHandler<CreateOrgCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateOrgCommand request, CancellationToken cancellationToken)
    {
        // 检查编号是否已存在。
        if (await repo.IsAnyAsync(m => m.Code == request.Org.Code, cancellationToken))
        {
            return Result.Failure("组织编号已存在");
        }

        var org = request.Org.Adapt<SysOrg>();
        var ok = await repo.InsertAsync(org, cancellationToken);
        return Result.From(ok);
    }
}
